﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mofang.Utils.LogProvider
{
	/// <summary>
	/// 字典表
	/// </summary>
	internal class DictCodeRepository
	{	
		/// <summary>
		/// 获取EF Context
		/// </summary>
		/// <returns></returns>
		public IDbConnection GetConnection()
		{
			
			return ConnectionService.GetMySqlConnection();			
			
		}

		/// <summary>
		/// 查询
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public DictCode Get(string id)
		{
			using (var conn = GetConnection())
			{
				string Table = typeof(DictCode).Name;

				var sqlCmd = string.Format("select * from {0} where Id=@id", Table);

				var entity = conn.Query<DictCode>(sqlCmd, new { id = id }).FirstOrDefault();

				return entity;
			}

			
		}

		/// <summary>
		/// 批量查询
		/// </summary>
		/// <param name="whereExp">Id=@id</param>
		/// <param name="param">new {id= logId }</param>
		/// <returns></returns>
		public List<DictCode> BatchGet(string whereExp,object param)
		{
			using (var conn = GetConnection())
			{
				string Table = typeof(DictCode).Name;

				var sqlCmd = string.Format("select * from {0} where {1}", Table, whereExp);

				var entities = conn.Query<DictCode>(sqlCmd, param).ToList();

				return entities;
			}
			
		}

		/// <summary>
		/// 新增
		/// </summary>
		/// <param name="code"></param>
		/// <returns></returns>
		public int Insert(DictCode code)
		{
			string query = string.Format("INSERT INTO {0}(Code,Parent,Name,Seq,EngName,PinYin,IsValid)VALUES(@Code,@Parent,@Name,@Seq,@EngName,@PinYin,@IsValid)"
				, typeof(DictCode).Name);

			using (var conn = GetConnection())
			{
				var result=conn.Execute(query, code);

				return result;

			}
		}

		/// <summary>
		/// 新增
		/// </summary>
		/// <param name="code"></param>
		/// <returns></returns>
		public int Update(DictCode code)
		{
			string query = string.Format("UPDATE {0} SET Code=@Code,Parent=@Parent,Name=@Name,Seq=@Seq,EngName=@EngName,PinYin=@PinYin,IsValid=@IsValid WHERE Id =@Id"
				, typeof(DictCode).Name);

			using (var conn = GetConnection())
			{
				var result = conn.Execute(query, code);

				return result;

			}
		}


	}

	
}
